package com.photons.timesync.socket

import com.photons.timesync.Constants
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.SocketException
import javax.inject.Inject

class UDPServer @Inject constructor() {
    private var socket: DatagramSocket? = null
    private var receivePacket: DatagramPacket? = null
    private val bufServer = ByteArray(Constants.BUFFER_LENGTH)
    private var thread: Thread? = null
    private var responseHandler: ResponseHandler? = null
    private var running = false

    interface ResponseHandler {
        fun onRequest(data: DatagramPacket?)
        fun genResponse(): ByteArray
    }

    fun start(port: Int, handler: ResponseHandler) {
        try {
            socket = DatagramSocket(port)
            receivePacket = DatagramPacket(bufServer, Constants.BUFFER_LENGTH)
            responseHandler = handler
            running = true
            startThread()
        } catch (e: SocketException) {
            e.printStackTrace()
        }
    }

    private fun startThread() {
        thread = Thread {
            try {
                while (running) {
                    socket!!.receive(receivePacket)
                    responseHandler?.onRequest(receivePacket)

                    val data = responseHandler?.genResponse() ?: continue
                    val sendPacket = DatagramPacket(
                        data,
                        data.size,
                        receivePacket!!.address,
                        receivePacket!!.port
                    )
                    socket?.send(sendPacket)
                    receivePacket?.length = Constants.BUFFER_LENGTH
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

        thread?.start()
    }
}